<template>
  <div class="other-data-container">
    <!-- 顶部导航栏 -->
    <div class="other-data-header">
      <div class="back-button" @click="goBack">
        <el-icon><ArrowLeft /></el-icon>
      </div>
      <div class="header-title">补充资料</div>
      <div class="placeholder"></div>
    </div>
    
    <!-- 提示信息 -->
    <div class="other-data-tip">
      上传补充资料有助于提高审核通过率~
    </div>
    
    <!-- 添加资料按钮 -->
    <div class="add-data-button-container">
      <el-button type="primary" class="add-data-button" @click="showAddDataDialog">
        <el-icon><Plus /></el-icon>
        添加资料
      </el-button>
    </div>
    
    <!-- 表单区域 -->
    <div class="other-data-form" v-if="dataItems.length > 0">
      <!-- 动态资料项 -->
      <div v-for="(item, index) in dataItems" :key="index" class="form-section">
        <div class="section-header">
          <div class="section-title">{{ item.name }}</div>
          <el-button type="danger" size="small" circle @click="removeDataItem(index)" class="remove-button">
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
        <div class="upload-area">
          <el-upload
            class="upload-component"
            action="#"
            :auto-upload="false"
            :on-change="(file) => handleFileChange(file, index)"
            list-type="picture-card"
            :file-list="getFileList(item)"
            :on-remove="(file) => handleFileRemove(file, index)"
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div class="upload-file">
                <img class="upload-image" :src="file.url" :alt="item.name" />
                <div class="upload-actions">
                  <el-icon class="upload-delete" @click.stop="() => handleFileRemove(file, index)"><Delete /></el-icon>
                </div>
              </div>
            </template>
          </el-upload>
          <div class="upload-tip">请上传清晰的{{ item.name }}</div>
        </div>
      </div>
    </div>
    
    <!-- 空状态提示 -->
    <div v-else class="empty-state">
      <el-empty description="暂无补充资料，请点击[添加资料]按钮添加"></el-empty>
    </div>
    
    <!-- 提交按钮 -->
    <div class="submit-button-container">
      <el-button type="primary" class="submit-button" @click="saveOtherData" :loading="loading">保存</el-button>
    </div>
    
    <!-- 添加资料对话框 -->
    <el-dialog
      v-model="addDataDialogVisible"
      title="添加资料"
      width="90%"
      :close-on-click-modal="false"
      class="add-data-dialog"
    >
      <el-form :model="newDataForm" ref="newDataFormRef" :rules="newDataFormRules" label-width="80px">
        <el-form-item label="资料名称" prop="name">
          <el-input v-model="newDataForm.name" placeholder="请输入资料名称"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDataDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addDataItem">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.other-data-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 顶部导航栏样式 */
.other-data-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  background-color: #3a4a6d;
  color: white;
  padding: 0 15px;
}

.back-button {
  font-size: 20px;
  cursor: pointer;
}

.header-title {
  font-size: 18px;
  font-weight: 500;
}

.placeholder {
  width: 20px;
}

/* 提示信息样式 */
.other-data-tip {
  background-color: #f0f0f0;
  padding: 10px 15px;
  font-size: 14px;
  color: #666;
}

/* 添加资料按钮样式 */
.add-data-button-container {
  padding: 15px;
  background-color: white;
  margin-top: 10px;
}

.add-data-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  border-radius: 4px;
  background-color: #6c5ce7;
  border-color: #6c5ce7;
}

/* 表单区域样式 */
.other-data-form {
  margin-top: 10px;
  background-color: white;
  padding: 15px;
}

.form-section {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.remove-button {
  font-size: 12px;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.upload-component {
  width: 100%;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.upload-file {
  position: relative;
  width: 100%;
  height: 100%;
}

.upload-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-actions {
  position: absolute;
  top: 0;
  right: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  cursor: pointer;
}

.upload-delete {
  font-size: 14px;
}

/* 空状态样式 */
.empty-state {
  margin-top: 10px;
  background-color: white;
  padding: 30px 15px;
  text-align: center;
}

/* 提交按钮样式 */
.submit-button-container {
  padding: 20px 15px;
  margin-top: auto;
}

.submit-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  border-radius: 4px;
  background-color: #3a4a6d;
  border-color: #3a4a6d;
}

/* 添加资料对话框样式 */
.add-data-dialog {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 15px;
  border-top: 1px solid #ebeef5;
}

/* 上传组件样式覆盖 */
:deep(.el-upload--picture-card) {
  width: 100%;
  height: 160px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  justify-content: center;
  align-items: center;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100%;
  height: 160px;
}
</style>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Plus, Delete } from '@element-plus/icons-vue'
import { useUserStore, useUserInfoStore } from '@/store'
import userService from '@/services/userService'

const router = useRouter()
const userStore = useUserStore()
const userInfoStore = useUserInfoStore()
const loading = ref(false)

// 添加资料对话框
const addDataDialogVisible = ref(false)
const newDataFormRef = ref(null)
const newDataForm = reactive({
  name: ''
})
const newDataFormRules = {
  name: [
    { required: true, message: '请输入资料名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

// 资料项列表
const dataItems = ref([])

// 初始化数据
onMounted(() => {
  initOtherData()
})

// 初始化其他数据
const initOtherData = () => {
  if (userInfoStore.state.detailInfo.otherData) {
    try {
      const data = JSON.parse(userInfoStore.state.detailInfo.otherData)
      console.log('原始数据:', data)
      // 数据: {自定义名1：[{图片1地址}，{图片2地址}]，自定义名2：[{图片3地址}，{图片4地址}]}
      if (!Array.isArray(data) && typeof data === 'object') {
        const newFormatItems = []
        
        // 遍历对象的所有键
        Object.keys(data).forEach(key => {
          const images = data[key]
          if (images.length > 0) {
            newFormatItems.push({
              name: key,
              images: images
            })
          }
        })

        dataItems.value = newFormatItems
      }
    } catch (error) {
      console.error('解析其他数据失败:', error)
    }
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 显示添加资料对话框
const showAddDataDialog = () => {
  newDataForm.name = ''
  addDataDialogVisible.value = true
}

// 添加资料项
const addDataItem = async () => {
  if (!newDataFormRef.value) return
  
  await newDataFormRef.value.validate((valid) => {
    if (!valid) return
    
    // 检查是否已存在同名资料
    const exists = dataItems.value.some(item => item.name === newDataForm.name)
    if (exists) {
      ElMessage.warning(`已存在名为"${newDataForm.name}"的资料`)
      return
    }
    
    // 添加新资料项
    dataItems.value.push({
      name: newDataForm.name,
      images: [],
    })
    
    // 关闭对话框
    addDataDialogVisible.value = false
    ElMessage.success(`已添加"${newDataForm.name}"资料项`)
  })
}

// 移除资料项
const removeDataItem = (index) => {
  dataItems.value.splice(index, 1)
}

// 获取文件列表
const getFileList = (item) => {
  if (!item.images) return [];
  return item.images.map((url, idx) => ({
    name: `${item.name}_${idx}`,
    url: url
  }));
}

// 处理文件变化
const handleFileChange = async(file, index) => {
  if (file.raw) {
    try {
      const response = await userService.uploadFile(userStore.userId, file.raw, "otherData");
      // 添加到图片列表
      if (!dataItems.value[index].images) {
        dataItems.value[index].images = []
      }
      dataItems.value[index].images.push(response.fileUrl)
      // 设置文件URL
      file.url = response.fileUrl
    } catch (error) {
      //TODO: 等待查看是否处理登录失效的上传失败
    }
  }
}

// 处理文件移除
const handleFileRemove = (file, index) => {
  // 从图片列表中移除
  const imageIndex = dataItems.value[index].images.findIndex(url => url === file.url)
  if (imageIndex !== -1) {
    dataItems.value[index].images.splice(imageIndex, 1)
  }
  
  // 强制更新组件
  dataItems.value = [...dataItems.value]
}

// 保存其他数据
const saveOtherData = async () => {
  loading.value = true
  
  try {
    // 检查是否有资料项
    if (dataItems.value.length === 0) {
      ElMessage.warning('请至少添加一种补充资料')
      loading.value = false
      return
    }
    
    // 检查是否每个资料项都有上传的图片
    const emptyItems = dataItems.value.filter(item => !item.images || item.images.length === 0)
    if (emptyItems.length > 0) {
      ElMessage.warning(`请为"${emptyItems[0].name}"上传图片`)
      loading.value = false
      return
    }
    
    // 转换为指定的JSON格式: {自定义名1：[{图片1地址}，{图片2地址}]，自定义名2：[{图片3地址}，{图片4地址}]}
    const formattedData = {}
    
    dataItems.value.forEach(item => {
      if (item.images && item.images.length > 0) {
        formattedData[item.name] = item.images
      }
    })
    // 准备用户数据
    const userData = {
      id: userStore.userId,
      otherData: JSON.stringify(formattedData)
    }
    // 调用服务更新用户信息
    const response = await userService.updateUserInfoAndReturn(userData)
    router.push('/user/profile')
  } finally {
    loading.value = false
  }
}
</script>